/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.managed;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import ru.ssau.datamanager.DataManager;
import ru.ssau.entities.DataAccessException;
import ru.ssau.entities.Thread;


@Named("thread")
@SessionScoped
public class ThreadBean implements Serializable {

    public static final String ADD = "Add thread";
    public static final String EDIT = "Edit thread";
    public static final String NO_THREAD_TO_EDIT = "noThreadToEdit";
    public static final String VIEW = "View";
    public static final String SEARCH = "Search threads";

    @EJB
    private DataManager dataManagera;

    private String searchParameter;
    private Integer selectedThreadId;
    private Thread currentThread;
    private String action;

    List<Thread> searchResult;

    public ThreadBean() {

    }

    public Integer getId() {
        if(currentThread == null) return null;
        return currentThread.getId();
    }

    public String getCaption() {
        if(currentThread == null) return null;
        return currentThread.getCaption();
    }

    public void setCaption(String caption) {
        currentThread.setCaption(caption);
    }

    //Получение параметра поиска (в окне поиска
    //каждый раз устанавливается пустое значение)
    public String getSearchParameter() {
        return "";
    }

    public void setSearchParameter(String searchParameter) {
        this.searchParameter = searchParameter;
    }

    //Формирование списка тредов для отображения
    public Map<String, Integer> getAllThreads() throws DataAccessException {
        Collection<Thread> threads = dataManagera.getAllThreads();
        Map<String, Integer> threadMap = new LinkedHashMap<String, Integer>();

        for(Thread thread: threads) {
            String description = String.format("%d. %s", thread.getId(), thread.getCaption());
            threadMap.put(description, thread.getId());
        }
        if(threadMap.size() < 1) {
            currentThread = null;
        }

        return threadMap;
    }

    //id текущего треда (того, который выбран для отображения)
    public Integer getSelectedThreadId() {
        return selectedThreadId;
    }

    public void setSelectedThreadId(Integer selectedThreadId) {
        this.selectedThreadId = selectedThreadId;
    }

    public void search() throws DataAccessException {
        Collection<Thread> foundThreads = dataManagera.findThreadsByCaption(searchParameter);
        searchResult = new LinkedList<Thread>(foundThreads);
        action = SEARCH;
    }

    public List<Thread> getSearchResult() {
        return searchResult;
    }

    public String getAction() {
        return action;
    }

    public void doAction() throws DataAccessException {
        if(action.equals(ADD)) {
            add();
        } else {
            edit();
        }
        selectedThreadId=null;
        action = VIEW;
    }

    public void add() throws DataAccessException {
        dataManagera.addThread(currentThread);
    }

    public void edit() throws DataAccessException {
        dataManagera.replaceThread(currentThread);
    }

    //Удаление сущности
    public void delete() throws DataAccessException {
        dataManagera.deleteThreadById(selectedThreadId);
        action = VIEW;
        currentThread = null;
    }

    //Удаление сущности из списка найденных
    public void deleteFromSearchResult(Thread thread) throws DataAccessException {
        dataManagera.deleteThreadById(thread.getId());
        searchResult.remove(thread);
        action = null;
    }

    public void editFromSearchResult(Thread thread) {
        currentThread = thread;
        action = EDIT;
    }

    public void setCurrentThread() throws DataAccessException {
        currentThread = dataManagera.getThreadById(selectedThreadId);
    }

    public void ensureCurrentThreadSet() throws DataAccessException {
        if(currentThread == null) {
            action = NO_THREAD_TO_EDIT;
        } else {
            //work around-ец. Опять.
            if(currentThread.getId() == null) {
                currentThread = dataManagera.getThreadById(selectedThreadId);
                if(currentThread == null) {
                    action = NO_THREAD_TO_EDIT;
                } else {
                    action = EDIT;
                }
            } else {
                action = EDIT;
            }
        }
    }

    public void unsetCurrentThread() {
        currentThread = new Thread();
        action = ADD;
    }
}
/*
 <!-- Thread section
        <h:form>
            Search thread by <i>caption</i> parameter:
            <br/>
            <h:inputText size="10" value="#{thread.searchParameter}" /> &nbsp;
            <h:commandButton value="Search" actionListener="#{thread.search}" action="#{thread.getAction}"/>
        </h:form>
        <br/>
        <h:form prependId="false">
            <table>
                <tr>
                    <td>
                        <h:selectOneMenu id="threadList" value="#{thread.selectedThreadId}">
                            <f:selectItems value="#{thread.allThreads}" />
                            <f:ajax render="id caption" listener="#{thread.setCurrentThread}"/>
                        </h:selectOneMenu>
                    </td>
                    <td>
                        <h:commandButton value="Add" actionListener="#{thread.unsetCurrentThread}" action="#{thread.getAction}"/>
                    </td>
                    <td>
                        <h:commandButton value="Edit" actionListener="#{thread.ensureCurrentThreadSet}" action="#{thread.getAction}"/>
                    </td>
                    <td>
                        <h:commandButton value="Delete" actionListener="#{thread.delete}" action="#{thread.getAction}"/>
                    </td>
                </tr>
            </table>
            <b>Id: </b>
            <h:outputText id="id" value="#{thread.id}"/>
            <br/>
            <b>Caption: </b>
            <h:outputText id="caption" value="#{thread.caption}">
        </h:form>
        <br/>-->
 */